package com.dny.asmtop.op;

import com.dny.asmtop.Command;
import com.dny.asmtop.MethodContext;
import jdk.internal.org.objectweb.asm.Type;
import jdk.internal.org.objectweb.asm.commons.GeneratorAdapter;

import java.util.Objects;

import static jdk.internal.org.objectweb.asm.Type.getType;

/**
 * Created by jlutt on 2018-01-17.
 * 新建数组
 *
 * @author jlutt
 */
public class CommandArrayNew implements Command {

  /**
   * 数组元素类型
   */
  private final Class<?> type;

  /**
   * 数组长度
   */
  private final Command length;

  public CommandArrayNew(Class<?> type, Command length) {
    this.type = type;
    this.length = length;
  }

  @Override
  public Type type(MethodContext context) {
    if (getType(type).getSort() == Type.ARRAY) {
      return getType(type);
    } else {
      return getType("[L" + type.getName() + ";");
    }
  }

  @Override
  public Type generator(MethodContext context) {
    GeneratorAdapter g = context.getGeneratorAdapter();

    length.generator(context);
    if (getType(type).getSort() == Type.ARRAY) {
      g.newArray(getType(getType(type).getDescriptor().substring(1)));
      return getType(type);
    } else {
      g.newArray(getType(type));
      return getType("[L" + type.getName() + ";");
    }
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    CommandArrayNew that = (CommandArrayNew) o;
    return Objects.equals(type, that.type) &&
        Objects.equals(length, that.length);
  }

  @Override
  public int hashCode() {

    return Objects.hash(type, length);
  }
}
